import utils.util as utils
import re


def _pre_replace(s):
    s = s.replace('\\widetilde', 'tilde')
    s = s.replace('s i n', 'sin')
    s = s.replace('c o s', 'cos')
    s = s.replace('t a n', 'tan')
    s = s.replace('c s c', 'csc')
    s = s.replace('s e c', 'sec')
    s = s.replace('c o t', 'cot')
    s = s.replace('\\sin', 'sin')
    s = s.replace('\\cos', 'cos')
    s = s.replace('\\tan', 'tan')
    s = s.replace('\\csc', 'csc')
    s = s.replace('\\sec', 'sec')
    s = s.replace('\\cot', 'cot')
    s = s.replace('\\ast', '*')
    s = s.replace('\\bullet', '*')
    s = s.replace('\\cdot', '*')
    s = s.replace('\\times', '×')
    s = s.replace('·', '*')
    # s = s.replace('×', '*')
    s = s.replace('•', '*')
    s = s.replace('÷', '/')
    s = s.replace('≠', '!=')
    s = s.replace('≤', '<=')
    s = s.replace('≥', '>=')
    s = utils.symbol_replace(s, '\\left', '')
    s = utils.symbol_replace(s, '\\right', '')
    s = s.replace('\\div', '/')
    s = s.replace('\\neq', '!=')
    s = utils.symbol_replace(s, '\\ne', '!=')
    s = s.replace('\\leq', '<=')
    s = s.replace('\\geq', '>=')
    s = utils.symbol_replace(s, '\\sfrac', '\\frac')
    s = utils.symbol_replace(s, '\\le', '<=')
    s = utils.symbol_replace(s, '\\ge', '>=')
    s = s.replace('\\rm ', '')
    s = s.replace('（', '(')
    s = s.replace('）', ')')
    s = s.replace('＝', '=')
    s = s.replace('，', ',')
    s = s.replace('；', ';')
    s = s.replace('：', ':')
    s = s.replace('\ ', ' ')
    s = s.replace('－', '-')
    s = s.replace('＋', '+')
    s = re.sub(r";\s*;", ";", s)
    s = s.replace("\u2060", "")
    return s


def _add_superscript_brace(s):
    i = s.find('^')
    while i != -1:
        i += 1
        if i < len(s) and s[i] != '{':
            j = i
            while j < len(s) and s[j].isalnum():
                j += 1
            s = s[:i] + '{' + s[i:j] + '}' + s[j:]
        i -= 1
        if s[i - 1] == ']':
            j = utils.bracket_match(s, i - 1)
            s = s[:j] + '{' + s[j:i] + '}' + s[i:]
        elif s[i - 1] == ')':
            j = utils.bracket_match(s, i - 1)
            s = s[:j] + '{' + s[j:i] + '}' + s[i:]
        elif s[i - 1] != '}':
            j = i - 1
            while j >= 0 and s[j].isalnum():
                j -= 1
            s = s[:j + 1] + '{' + s[j + 1:i] + '}' + s[i:]
        i = s.find('^', i + 1)

    return s


def _replace_brackets(s: str):
    chars = list(s)
    flag = 0
    for i in range(len(chars)):
        if chars[i] == 's' and "".join(chars[i:i + 4]) == "sin{" and flag == 0:
            flag = 1
            chars[i + 3] = '('
        elif chars[i] == 'c' and "".join(chars[i:i + 4]) == "cos{" and flag == 0:
            flag = 1
            chars[i + 3] = '('
        elif chars[i] == 't' and "".join(chars[i:i + 4]) == "tan{" and flag == 0:
            flag = 1
            chars[i + 3] = '('
        elif flag > 0 and chars[i] == "{":
            flag += 1
        elif flag > 0 and chars[i] == '}':
            flag -= 1
            if flag == 0:
                chars[i] = ")"
    return "".join(chars)


def _remove_comments(s):
    # s = re.sub(r"/\*[\s\S]*?\*/\r?\n?", "", s)
    # s = re.sub(r"//[^\r\n]*", "", s)
    return s


# e_{orbit}^ --> {e_{orbit}}^
def _topandsub_addbraces(s):
    # 替换为括号内的内容
    s = re.sub(r'\\mathbit{([^}]+)}', r'\1', s)
    s = re.sub(r'\\mathbf{([^}]+)}', r'\1', s)
    s = re.sub(r'\\mathrm\{([^\}]+)\}', r'\1', s)
    s = re.sub(r"([a-zA-Z0-9])_\{([^\}]+)\}\^", r"{\1_{\2}}^", s)
    return s


# [0 0 0 1]T --> {[0 0 0 1]}^{T}
def _matrix_transpose(s):
    i = s.find(']T')
    while i != -1:
        j = utils.bracket_match(s, i)
        s = s[:j] + '{' + s[j:i + 1] + '}^{T}' + s[i + 2:]
        i = s.find(']T')
    return s


def add_semicolon(s):
    str_list = s.split('\r\n')
    for i in range(len(str_list)):
        if str_list[i].strip() == '':
            continue
        if str_list[i].strip().endswith(';'):
            continue
        if str_list[i].strip().endswith('{') or str_list[i].strip() == '}':
            continue
        if (str_list[i].strip().lower().startswith(('if', 'for', '若', '如果', 'while', 'switch'))) \
                and (str_list[i].strip().endswith(')') or str_list[i].strip().endswith('{')):
            continue
        if _checkif(str_list[i].strip().lower()) != 0:
            continue
        if str_list[i].strip().lower().startswith(('else', 'endif', 'endfor', 'endwhile', 'endswitch', '否则')):
            continue
        str_list[i] = str_list[i] + ';'
    return '\r\n'.join(str_list)


def _checkif(s):
    brackets = 0
    for c in s:
        if c == '(':
            brackets += 1
        elif c == ')':
            brackets -= 1
    return brackets


def pre_process(s, dict=False):
    if dict:
        s = _pre_replace(s)
        s = _topandsub_addbraces(s)
        s = _add_superscript_brace(s)
        s = _matrix_transpose(s)
        return s

    s = _remove_comments(s)
    s = _add_parentheses_to_conditions(s)
    s = _pre_replace(s)
    s = _topandsub_addbraces(s)
    s = _add_superscript_brace(s)
    s = _matrix_transpose(s)
    while True:  # 替换sin后面为小括号
        i = s.find('sin{')
        if i == -1:
            i = s.find('cos{')
        if i == -1:
            i = s.find('tan{')
        if i == -1:
            break
        s = _replace_brackets(s)
    return s


def _add_parentheses_to_conditions(code_str):
    # 定义匹配 IF/ELSEIF 后面条件表达式的正则表达式
    pattern = r'(?<!\S)(ELSE\s*)?(IF\d*)\s+(?!\()\s*([^\r\n\/\/]+)'

    def repl(match):
        # Construct the replacement string with parentheses around the condition
        return f"{match.group(1) or ''}{match.group(2)} ({match.group(3).strip()})"

    modified_string = re.sub(pattern, repl, code_str, flags=re.IGNORECASE)
    return modified_string


if __name__ == '__main__':
    s = ' for (a=1){  '
    print(s.strip().startswith(('if', 'for', '如果', 'while')))
